<?php

/**
 * Albireo Kernel
 *
 * @copyright  Copyright (c) 2010 Albireo Solutions
 * @package    Kernel
 */

namespace KernelModule;

use Nette\Object;
use Nette\Security\AuthenticationException;
use Nette\Security\Identity;
use Nette\Security\Iauthenticator;

use Celebrio\ShadowReader;

use Celebrio\AccessControl\AclConstants;
use Celebrio\PasswordHasher;

use \InvalidArgumentException;

/**
 * Masteruser authenticator.
 *
 * @author     Albireo Solutions
 * @package    Kernel
 */
class KernelMasterAuthenticator extends Object implements IAuthenticator {

    /**
     * Performs an authentication for the ROOT_USER.
     *
     * @param array $credentials sign in credentials
     * @return \Nette\Security\Identity|\Nette\Security\IIdentity
     * @throws \Nette\Security\AuthenticationException
     */
    public function authenticate(array $credentials) {
        if ($credentials[self::USERNAME] !== AclConstants::ROOT_USER) {
            throw new AuthenticationException(_("Only root can sign in to the critical mode."));
        }
        if (strcasecmp(ShadowReader::PASSWORD, hash('sha1', $credentials[self::PASSWORD])) === 0) {
            $data[self::PASSWORD] = PasswordHasher::userHash($credentials[self::USERNAME], $credentials[self::PASSWORD]);
            return new Identity(AclConstants::ROOT_USER, array(AclConstants::ROOT_ROLE), $data);
        }
        throw new AuthenticationException(_("Invalid password."), self::INVALID_CREDENTIAL);
    }

}